package com.justreading.order.utils;


import com.justreading.order.constant.TokenConstant;
import com.justreading.order.exception.InvalidateTokenException;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author LYJ
 * @Description 用于创建token的工具类
 * @date 2021 年 02 月 24 日 10:36
 */
@Component
public class TokenManager {

    private static final String TOKEN_NAME = "token";

    @Autowired
    private RedisUtil redisUtil;
    
//    @Value("token.expiration")
    private static long tokenExpiration = 20 * 24 * 60 * 60 * 1000;


//    @Value("token.signKey")
    private static String tokenSignKey = "123456";

    //1 使用jwt根据用户名生成token
    public  String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
    }

    //2 根据token字符串得到用户信息
    public  String getUserInfoFromToken(String token) {
        return Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
    }

    //3 删除token
    public  void removeToken(String token) {

    }

    // 校验token
    public boolean checkToken(HttpServletRequest request) throws InvalidateTokenException{
        String token = request.getHeader(TOKEN_NAME);
        if(ObjectUtils.isEmpty(token)){
            throw new InvalidateTokenException("非法请求",401);
        }
        if(ObjectUtils.isEmpty(redisUtil.get(TokenConstant.TOKEN_USER_ENTITY_PRE + token))){
            throw  new InvalidateTokenException("登录超时",201);
        }
        return true;
    }
}
